package com.dongdongshop.controller;

import com.dongdongshop.domain.AjaxResult;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbAdmin;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("userController")
public class UserController {

    @DubboReference(timeout = 50000)
    private UserService userService;

    //用户登录功能
    @RequestMapping("login")
    @ResponseBody
    public AjaxResult login(TbUser user){
        //shiro 登录
        //获取用户主体
        Subject subject = SecurityUtils.getSubject();
        //封装 token
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        //登录
        try {
            subject.login(token);
            return AjaxResult.OK();
        } catch (UnknownAccountException u) { //未知帐户异常
            return AjaxResult.R(ResultEnum.ACCOUNT_DOES_NOT);
        }catch (IncorrectCredentialsException i){ // 不正确的凭据异常
            return AjaxResult.R(ResultEnum.WRONG_PASSWORD);
        }
    }

    // 修改密码
    @RequestMapping("updatePwd")
    @ResponseBody
    public AjaxResult updatePwd(String username){
        if (StringUtils.isEmpty(username)){
            return AjaxResult.R(ResultEnum.PARAMETER_EMPTY);
        }
        try {
            userService.updatePwd(username);
            return AjaxResult.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }


}
